package org.amphiprion.rfreplayanalyser.ui;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import org.amphiprion.rfreplayanalyser.parser.Replay;
import org.amphiprion.rfreplayanalyser.parser.ReplayParserTask;
import org.amphiprion.rfreplayanalyser.ui.lapanalyzer.LapAnalyzerFrame;
import org.amphiprion.rfreplayanalyser.ui.progress.ProgressDialog;
import org.amphiprion.rfreplayanalyser.ui.race.RaceFrame;
import org.amphiprion.rfreplayanalyser.util.PreferenceApplication;

@SuppressWarnings("serial")
public class MainFrame extends JFrame {
	private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("org.amphiprion.rfreplayanalyser.ui.messages"); //$NON-NLS-1$

	private JPanel contentPane;
	private JTextField txtReplay;
	private Replay replay;
	private JTextField txtCollisionXSize;
	private JTextField txtCollisionYSize;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					MainFrame frame = new MainFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainFrame() {
		setTitle(BUNDLE.getString("MainFrame.this.title")); //$NON-NLS-1$
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 653, 290);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblLogo = new JLabel(); //$NON-NLS-1$
		lblLogo.setBounds(174, 5, 288, 49);
		lblLogo.setIcon(new ImageIcon(MainFrame.class.getResource("/org/amphiprion/rfreplayanalyser/ui/gentlemen_racers.png")));
		contentPane.add(lblLogo);

		JLabel lblNewLabel = new JLabel(BUNDLE.getString("MainFrame.lblNewLabel.text")); //$NON-NLS-1$
		lblNewLabel.setBounds(237, 74, 163, 34);
		lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 28));
		contentPane.add(lblNewLabel);

		JButton btnNewButton_1 = new JButton(BUNDLE.getString("MainFrame.btnNewButton_1.text_1")); //$NON-NLS-1$
		btnNewButton_1.setBounds(156, 214, 163, 23);
		btnNewButton_1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				launchRaceAnalyzer();
			}
		});

		JLabel lblWidth = new JLabel(BUNDLE.getString("MainFrame.lblWidth.text")); //$NON-NLS-1$
		lblWidth.setHorizontalAlignment(SwingConstants.CENTER);
		lblWidth.setBounds(285, 135, 55, 14);
		contentPane.add(lblWidth);

		JLabel lblLongueur = new JLabel(BUNDLE.getString("MainFrame.lblLongueur.text")); //$NON-NLS-1$
		lblLongueur.setHorizontalAlignment(SwingConstants.CENTER);
		lblLongueur.setBounds(350, 135, 71, 14);
		contentPane.add(lblLongueur);

		JLabel lblMinimumDistanceFor = new JLabel(BUNDLE.getString("MainFrame.lblMinimumDistanceFor.text")); //$NON-NLS-1$
		lblMinimumDistanceFor.setHorizontalAlignment(SwingConstants.RIGHT);
		lblMinimumDistanceFor.setBounds(10, 160, 265, 14);
		contentPane.add(lblMinimumDistanceFor);

		txtCollisionXSize = new JTextField();
		txtCollisionXSize.setBounds(285, 157, 55, 20);
		txtCollisionXSize.setText(BUNDLE.getString("MainFrame.textField.text")); //$NON-NLS-1$
		contentPane.add(txtCollisionXSize);
		txtCollisionXSize.setColumns(10);

		txtCollisionYSize = new JTextField();
		txtCollisionYSize.setBounds(360, 157, 50, 20);
		txtCollisionYSize.setText(BUNDLE.getString("MainFrame.txtTxtcollisionysize.text")); //$NON-NLS-1$
		contentPane.add(txtCollisionYSize);
		txtCollisionYSize.setColumns(10);

		JLabel lblReplay = new JLabel(BUNDLE.getString("MainFrame.lblReplay.text")); //$NON-NLS-1$
		lblReplay.setHorizontalAlignment(SwingConstants.RIGHT);
		lblReplay.setBounds(10, 189, 146, 14);
		contentPane.add(lblReplay);

		txtReplay = new JTextField();
		txtReplay.setBounds(156, 186, 332, 20);
		contentPane.add(txtReplay);
		txtReplay.setColumns(10);

		JButton btBrowse = new JButton(BUNDLE.getString("MainFrame.btnNewButton_1.text")); //$NON-NLS-1$
		btBrowse.setBounds(496, 185, 88, 23);
		btBrowse.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent event) {
				final JFileChooser fc = new JFileChooser();
				// In response to a button click:
				int returnVal = fc.showOpenDialog((JButton) event.getSource());
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					chooseReplay(fc.getSelectedFile());
				}
			}
		});
		contentPane.add(btBrowse);
		contentPane.add(btnNewButton_1);

		JButton btnNewButton = new JButton(BUNDLE.getString("MainFrame.btnNewButton.text")); //$NON-NLS-1$
		btnNewButton.setBounds(325, 214, 163, 23);
		btnNewButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				launchLapAnalyzer();
			}
		});
		contentPane.add(btnNewButton);

		txtCollisionXSize.setText(PreferenceApplication.read("minWithToTriggerTouchEvent", "1.8"));
		txtCollisionYSize.setText(PreferenceApplication.read("minHeightToTriggerTouchEvent", "4.3"));
		txtReplay.setText(PreferenceApplication.read("replayFilename", ""));
	}

	private void chooseReplay(File replayfile) {
		txtReplay.setText(replayfile.getAbsolutePath());
	}

	private boolean parseReplayIfNeeded() {
		if (txtReplay.getText().isEmpty()) {
			// TODO remove and use persisted preference
			txtReplay.setText("C:\\Users\\Amphiprion\\rFactor\\ReplayFridge\\Replays\\Road Atlanta SR 44");
			txtReplay.setText("C:\\Users\\Amphiprion\\rFactor\\ReplayFridge\\Replays\\JPC-Suzuka2013 1.0 SR 12");
		}
		float minWithToTriggerTouchEvent = 1.8f;
		float minHeightToTriggerTouchEvent = 4.3f;
		try {
			minWithToTriggerTouchEvent = Float.parseFloat(txtCollisionXSize.getText().replace(',', '.'));
		} catch (Throwable e) {
			txtCollisionXSize.setText("1.8");
		}
		try {
			minHeightToTriggerTouchEvent = Float.parseFloat(txtCollisionYSize.getText().replace(',', '.'));
		} catch (Throwable e) {
			txtCollisionYSize.setText("4.3");
		}
		if (replay != null && txtReplay.getText().equals(replay.getFilename()) && replay.minWithToTriggerTouchEvent == minWithToTriggerTouchEvent && replay.minHeightToTriggerTouchEvent == minHeightToTriggerTouchEvent) {
			return true;
		}
		File file = new File(txtReplay.getText());
		if (!file.exists()) {
			ErrorDialog.showError("<html>Cannot find " + file.getAbsolutePath() + "</html>", this);
			return false;
		}

		PreferenceApplication.writeFloat("minWithToTriggerTouchEvent", minWithToTriggerTouchEvent);
		PreferenceApplication.writeFloat("minHeightToTriggerTouchEvent", minHeightToTriggerTouchEvent);
		PreferenceApplication.write("replayFilename", txtReplay.getText());
		PreferenceApplication.commit();

		ReplayParserTask task = new ReplayParserTask(file, minWithToTriggerTouchEvent, minHeightToTriggerTouchEvent);
		boolean succeed = ProgressDialog.launchWork(this, task);
		if (succeed) {
			replay = task.getReplay();
		} else {
			replay = null;
		}
		return succeed;
	}

	private void launchLapAnalyzer() {
		if (parseReplayIfNeeded()) {
			LapAnalyzerFrame.show(replay);
		}
	}

	private void launchRaceAnalyzer() {
		if (parseReplayIfNeeded()) {
			RaceFrame.show(replay);
		}
	}
}
